<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
            <el-form-item label="用户名称" prop="nickName">
                <el-input v-model="queryParams.nickName" placeholder="请输入名称" clearable maxlength="10" show-word-limit
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="部门" prop="enterpriseDeptId">
                <!-- <el-cascader style="width: 300px;" v-model="value" :options="options" :props="{ checkStrictly: true }"
                    @change="handleCascaderChange($event, 'query')"></el-cascader> -->

                <el-select v-model="queryParams.enterpriseDeptId">
                    <el-option v-for="item in options" :key="item.value" :value="item.value"
                        :label="item.label"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-form-item label="预警状态" prop="appraisalAbnormalStatus">
                    <el-select v-model="queryParams.appraisalAbnormalStatus" placeholder="预警状态" clearable
                        style="width: 240px">
                        <el-option v-for="dict in dict.type.abnormalstatus" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item></el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-col :span="1.5">
                    <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple"
                        @click="handleDelete" v-hasPermi="['business:companyevaluationReport:remove']">删除</el-button>
                </el-col>
                <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['business:historyEvalution:export']">导出</el-button>
                <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExportMember"
                    :disabled="multiple" v-hasPermi="['business:historyEvalution:exportmember']">导出人员</el-button>
                          <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExportScl"
                    v-hasPermi="['business:historyEvalutionScl:export']">导出分区报告</el-button>
                </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table v-loading="loading" :data="configurationList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" align="center" width="55" type="index" />


            <el-table-column label="测评名称" align="center" prop="appraisalName" min-width="200"
                :show-overflow-tooltip="true" />
            <!-- <el-table-column label="厂区名称" align="center" prop="factoryName" min-width="150"
                :show-overflow-tooltip="true" /> -->
            <el-table-column label="部门名称" align="center" prop="enterpriseDeptName" min-width="150"
                :show-overflow-tooltip="true" />
            <el-table-column label="姓名" align="center" prop="nickName" min-width="100" :show-overflow-tooltip="true" />
            <el-table-column label="联系电话" align="center" prop="phonenumber" min-width="130"
                :show-overflow-tooltip="true" />
            <el-table-column label="性别" align="center" prop="userSex" min-width="100" :show-overflow-tooltip="true">
                <template v-slot="scope">
                    <div v-if="scope.row.userSex == 0">男</div>
                    <div v-if="scope.row.userSex == 1">女</div>
                </template>
            </el-table-column>
            <el-table-column label="得分" align="center" prop="appraisalScore" min-width="100"
                :show-overflow-tooltip="true" />
            <el-table-column label="预警状态" align="center" prop="appraisalAbnormalStatus" min-width="100"
                :show-overflow-tooltip="true">
                <template v-slot="scope">
                    <el-tag :type="dictValueToTagType(scope.row.appraisalAbnormalStatus)">
                        {{ getDictLabel('abnormalstatus', scope.row.appraisalAbnormalStatus)
                        }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="评测状态" align="center" prop="appraisalStatus" min-width="100"
                :show-overflow-tooltip="true">
                <template v-slot="scope">
                    <div v-if="scope.row.appraisalStatus == 0">进行中</div>
                    <div v-if="scope.row.appraisalStatus == 1">已完成</div>
                </template>
            </el-table-column>
            <el-table-column label="开始时间" align="center" prop="appraisalBeginDate" min-width="160"
                :show-overflow-tooltip="true" />
            <el-table-column label="结束时间" align="center" prop="appraisalFinishDate" min-width="160"
                :show-overflow-tooltip="true" />

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="80">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="handleViews(scope.row)">查看报告</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        <el-dialog title="评测结果分析" :visible.sync="openResult" width="700px" append-to-body>
            <scl90-vue ref="scl90Ref" :appraisalId="appraisalId" :detailId="detailId"
                v-if="appraisalId == 8"></scl90-vue>
            <anxiety-self-assessment ref="anxietyRef" :appraisalId="appraisalId" :detailId="detailId"
                v-if="appraisalId == 7"></anxiety-self-assessment>
            <burnout ref="burnoutRef" :appraisalId="appraisalId" :detailId="detailId" v-if="appraisalId == 1"></burnout>
            <careerInterest ref="careerRef" :appraisalId="appraisalId" :detailId="detailId" v-if="appraisalId == 5">
            </careerInterest>
            <childRelationshipAssessment ref="AssessmentRef" :appraisalId="appraisalId" :detailId="detailId"
                v-if="appraisalId == 10">
            </childRelationshipAssessment>
            <childRelationshipDiagnosis ref="DiagnosisRef" :appraisalId="appraisalId" :detailId="detailId"
                v-if="appraisalId == 4">
            </childRelationshipDiagnosis>
            <depressionSelfAssessment ref="depressionRef" :appraisalId="appraisalId" :detailId="detailId"
                v-if="appraisalId == 2">
            </depressionSelfAssessment>
            <maritalQuality ref="maritalRef" :appraisalId="appraisalId" :detailId="detailId" v-if="appraisalId == 9">
            </maritalQuality>
            <perceivedStress ref="stressRef" :appraisalId="appraisalId" :detailId="detailId" v-if="appraisalId == 6">
            </perceivedStress>
            <socialSupportRatingScale ref="socialSupportRef" :appraisalId="appraisalId" :detailId="detailId"
                v-if="appraisalId == 3"></socialSupportRatingScale>
        </el-dialog>


         <el-dialog title="导出区分报告" :visible.sync="openexportReport" width="700px" append-to-body>
            <el-form ref="formReport" :model="formReport" :rules="rulesReport" label-width="80px">
                <el-form-item label="部门" prop="enterpriseDeptId">
                    <el-select v-model="formReport.enterpriseDeptId">
                        <el-option v-for="item in options" :key="item.value" :value="item.value"
                            :label="item.label"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import VueHtml2pdf from 'vue-html2pdf'
import scl90Vue from '../cnps/scl90.vue'; //8
import anxietySelfAssessment from '../cnps/anxietySelfAssessment.vue'; //焦虑自我评估7
import burnout from '../cnps/burnout.vue'; //职业倦怠1
import careerInterest from '../cnps/careerInterest.vue'; //霍兰德职业兴趣5
import childRelationshipAssessment from '../cnps/childRelationshipAssessment.vue'; //亲子关系诊断10
import childRelationshipDiagnosis from '../cnps/childRelationshipDiagnosis.vue'; //亲子关系评估4
import depressionSelfAssessment from '../cnps/depressionSelfAssessment.vue'; //抑郁自我评估2
import maritalQuality from '../cnps/maritalQuality.vue'; //婚姻9
import perceivedStress from '../cnps/perceivedStress.vue'; //知觉压力6
import socialSupportRatingScale from '../cnps/socialSupportRatingScale.vue'; //社会支持评分量表3
import { userAppraisalList1, delappraisal } from '@/api/member'
import {exportSclWord4, enterpriseUser ,exportSDSWord,exportSASWord,exportSclWord} from '@/api/evaluationReport/index.js'
export default {
    name: "ConfigurationMemberReport",
    dicts: ['abnormalstatus', 'sys_user_sex'],
    components: {
        VueHtml2pdf,
        scl90Vue,
        anxietySelfAssessment,
        burnout,
        careerInterest,
        childRelationshipAssessment,
        childRelationshipDiagnosis,
        depressionSelfAssessment,
        maritalQuality,
        perceivedStress,
        socialSupportRatingScale
    },
    data() {
        return {
             rulesReport: {
                enterpriseDeptId: [
                    { required: true, message: "部门不能为空", trigger: "blur" }
                ],
            },
            openexportReport: false,
            formReport: {},
            options: [],
            value: [],
            appraisalId: '',
            detailId: '',
            openResult: false,
            appraisalListData: [],
            dates: [],
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 配置维护表格数据
            configurationList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            idsList: [],
            // 查询参数
            queryParams: {
                appraisalAbnormalStatus: undefined,
                nickName: undefined,
                enterpriseDeptId: undefined,
                enterpriseId: undefined,
                factoryId: undefined,
                enterpriseName: undefined, factoryName: undefined, enterpriseDeptName: undefined,
                pageNum: 1,
                pageSize: 10,
                userType: 2,
                qrId: ''
            }
        };
    },
    created() {
        this.getList()
        enterpriseUser().then(res => {
            console.log(this.$route.query.enterpriseId)
            let rows = res.rows.filter(item => {
                return item.parentId == this.$route.query.enterpriseId;
            });
            rows.forEach(element => {
                element.value = element.id
                element.label = element.enterpriseName
            });
            this.options = rows
            // // 使用示例
            // const processedData = this.formatData(this.options);
        })
    },
    methods: {
        /** 删除按钮操作 */
        handleDelete() {
            const ids = this.idsList
            this.$modal.confirm('是否确认删除报告数据项？').then(function () {
                return delappraisal(ids)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess("删除成功")
            }).catch(() => { })
        },
        getDictLabel(dictType, value) {
            let type = ""
            this.dict.type.abnormalstatus.forEach(item => {
                if (item.value == value) {
                    type = item.label
                }
            })
            return type
        },
        dictValueToTagType(status) {
            let type = ""
            this.dict.type.abnormalstatus.forEach(item => {
                if (item.value == status) {
                    type = item.raw.listClass
                }
            })
            return type
        },
        handleCascaderChange(value, type) {
            this.queryParams.factoryId = value[0] || '';
            this.queryParams.enterpriseDeptId = value[1] || '';
        },
         handleExportScl() {
            this.openexportReport = true
        },
        formatData(data) {
            for (let i = 0; i < data.length; i++) {
                if (data[i].children && data[i].children.length === 0) {
                    data[i].children = undefined; // 关键步骤
                } else if (data[i].children) {
                    this.formatData(data[i].children); // 递归处理子级
                }
            }
            return data;
        },
           /** 提交按钮 */
        submitForm: function () {
            this.$refs["formReport"].validate(valid => {
                if (valid) {
                    const loading = this.$loading({
                        lock: true,
                        text: '正在导出中，请在导出列表中查看',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });
                    let form = {}
                    if (this.ids.length > 0) {
                        form = {
                            qrId: this.$route.query.id,
                            userIds: this.ids
                        }
                    } else {
                        form = {
                            qrId: this.$route.query.id,
                            enterpriseDeptId: this.formReport.enterpriseDeptId,
                        }
                    }
                    exportSclWord4(form).then(res => {

                    })
                    // this.download(downLoadUrl, form, `报告_${new Date().getTime()}.zip`)


                    setTimeout(() => {
                        loading.close();
                        this.openexportReport = false
                    }, 3000);
                }
            })
        },
        handleExportMember() {
            this.download("/business/appraisal/exportMember", {
                ids: this.ids
            }, `导出人员_${new Date().getTime()}.xlsx`)
        },
        /** 导出按钮操作 */
        handleExport() {
            // let downLoadUrl = ''
            const loading = this.$loading({
                lock: true,
                text: '正在导出中，请在导出列表中查看',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            let form = {}
            if (this.ids.length > 0) {
                form = {
                    qrId: this.$route.query.id,
                    userIds: this.ids
                }
            } else {
                form = {
                    qrId: this.$route.query.id,
                    enterpriseDeptId: this.queryParams.enterpriseDeptId,
                    appraisalAbnormalStatus: this.queryParams.appraisalAbnormalStatus
                }
            }
            if (this.$route.query.appraisalId == 2) {
                exportSDSWord(form).then(res => {

                })
            }
            if (this.$route.query.appraisalId == 7) {
                exportSASWord(form).then(res => {

                })
            }
            if (this.$route.query.appraisalId == 8) {
                exportSclWord(form).then(res => {

                })
            }
            // this.download(downLoadUrl, form, `报告_${new Date().getTime()}.zip`)


            setTimeout(() => {
                loading.close();
            }, 3000);
        },
        generateReport() {
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            setTimeout(() => {
                this.$refs.html2Pdf.generatePdf()
                loading.close();
            }, 2000);
        },
        handleViews(row) {
            this.appraisalId = row.appraisalId;
            this.detailId = row.id;
            this.openResult = true
        },
        changeDate(e) {
            this.queryParams.appraisalBeginDate = e[0]
            this.queryParams.appraisalFinishDate = e[1]
        },
        /** 查询配置维护列表 */
        getList() {
            this.loading = true;
            this.queryParams.qrId = this.$route.query.id
            userAppraisalList1(this.queryParams).then(response => {
                this.configurationList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
           // 取消按钮
        cancel() {
            this.openexportReport = false
            this.resetReport();
        },
        resetReport() {
            this.formReport = {
                enterpriseDeptId: undefined,
            }
            this.resetForm("formReport")
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dates = []
            this.queryParams.enterpriseName = null
            this.queryParams.factoryName = null
            this.queryParams.enterpriseDeptName = null
            this.queryParams.enterpriseId = null
            this.queryParams.factoryId = null
            this.queryParams.enterpriseDeptId = null
            this.value = []
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.userId)
            this.idsList = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        }
    }
};
</script>
